package com.atguigu.dga.dolphinscheduler.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.dga.dolphinscheduler.bean.TDsTaskDefinition;
import com.atguigu.dga.dolphinscheduler.mapper.TDsTaskDefinitionMapper;
import com.atguigu.dga.dolphinscheduler.service.TDsTaskDefinitionService;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liuxu
 * @since 2023-10-13
 */
@Service
@DS("dolphinscheduler")
public class TDsTaskDefinitionServiceImpl extends ServiceImpl<TDsTaskDefinitionMapper, TDsTaskDefinition> implements TDsTaskDefinitionService {

    @Override
    public List<TDsTaskDefinition> selecList() {
        List<TDsTaskDefinition> list = list();
        //单独把sql提取出来
        for (TDsTaskDefinition tDsTaskDefinition : list) {
            extractSql(tDsTaskDefinition);
        }


        return list;
    }

    private void extractSql(TDsTaskDefinition tDsTaskDefinition) {
        String taskParams = tDsTaskDefinition.getTaskParams();
        JSONObject taskParamsObject = JSONObject.parseObject(taskParams);

        //提取rawscript
        String rawScript = taskParamsObject.getString("rawScript");

        //判断是否有rawScript
        if(rawScript == null || rawScript.trim().isEmpty()){
            return;
        }

        //开始截取sql语句

        //查找开始位置
        int startIndex=0;
        int withIndex=rawScript.indexOf("with");
        if (withIndex==-1){
            startIndex=rawScript.indexOf("insert");
        }else {
            startIndex=withIndex;
        }
        if(startIndex==-1){
            //未找到,判定无sql语句
            return;
        }

        //查找结束位置
        int endIndex=0;
        int fenhaoIndex=rawScript.indexOf(";",startIndex);
        if (fenhaoIndex==-1){
            endIndex=rawScript.indexOf("\"",startIndex);
        }else {
            endIndex=fenhaoIndex;
        }

        //截取sql字符串
        String substring = rawScript.substring(startIndex, endIndex);

        tDsTaskDefinition.setTsakSQL(substring);

    }
}
